//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using OpenLS.Spreadsheet.Extensibility;

namespace OpenLS.Spreadsheet.Extensibility
{
    public class RangeToDoubleArrayConverterAttribute: ParameterConverterAttribute
    {
        internal override void ConvertImp(ConversionData data)
        {
            if (data.Value is IRange && data.TargetType == typeof(double[]))
                data.Result = RangeToDoubleArray((IRange)data.Value);
        }

        public static  double []RangeToDoubleArray(IRange range)
        {
            List<double> result = new List<double>();
            foreach (ICell cell in range.GetNonEmptyCells())
            {
                object o = cell.Value;
                if (o is double)
                {
                    result.Add((double)o);
                }
            }
            double[] result2 = new double[result.Count];
            result.CopyTo(result2);
            return result2;
        }
        public static double[] RangeToDoubleArrayNoSubTotal(IRange range)
        {
            List<double> result = new List<double>();
            foreach (ICell cell in range.GetNonEmptyCells())
            {
                object o = cell.Value;
                if (o is double)
                {
                    if (HasSubTotal(cell))
                        continue;
                    result.Add((double)o);
                }
            }
            double[] result2 = new double[result.Count];
            result.CopyTo(result2);
            return result2;
        }
        static bool HasSubTotal (ICell cell)
        {
            return cell.ContainsFunction("SUBTOTAL");
        }

     /*  static bool HasSubTotal(Expression exp)
        {
            if (exp == null)
                return false;
            foreach (Expression e in GetAllExpressions(exp))
            {
                if (e is FunctionInvokeExpression)
                {
                    FunctionInvokeExpression fe = (FunctionInvokeExpression)e;
                    if (fe.Function.Name == "SUBTOTAL")
                        return true;
                }
            }
            return false;
        }
        static IEnumerable<Expression> GetAllExpressions(Expression exp)
        {
            yield return NonSharedExpression(exp);
            foreach (Expression e in exp.GetSubExpressions())
            {
                foreach (Expression ee in GetAllExpressions(e))
                {
                    yield return NonSharedExpression(ee);
                }
            }
        }
        static Expression NonSharedExpression(Expression e)
        {
            if (e is SharedExpressionReference)
            {
                SharedExpressionReference se = (SharedExpressionReference)e;
                return se.ActualExpression;
            }
            return e;
        }
*/

    }
}
